.SUFFIXES: .cpp .cu .cu_dbg.o .c_dbg.o .cpp_dbg.o .cu_rel.o .c_rel.o .cpp_rel.o .cubin .ptx
.PRECIOUS: %.o

CUQU := ../../cuqu

CUDA_INSTALL_PATH ?= /usr/local/cuda

# fine on RHEL/CO/SL 5.x
MPI_INSTALL_PATH ?= /usr/lib64/openmpi/1.4-gcc

ifdef cuda-install
	CUDA_INSTALL_PATH := $(cuda-install)
endif

# detect OS
OSUPPER   = $(shell uname -s 2>/dev/null | tr [:lower:] [:upper:])
OSLOWER   = $(shell uname -s 2>/dev/null | tr [:upper:] [:lower:])
ifndef OS
  OSNAME := $(shell uname)
endif

# 'linux' is output for Linux system, 'darwin' for OS X
DARWIN = $(strip $(findstring DARWIN, $(OSUPPER)))
ifneq ($(DARWIN),)
   SNOWLEOPARD = $(strip $(findstring 10.6, $(shell egrep "<string>10\.6" /System/Library/CoreServices/SystemVersion.plist)))
endif

# detect 32-bit or 64-bit platform
HP_64 = $(shell uname -m | grep 64)
OSARCH= $(shell uname -m)

VERBOSE   :=
NVCC      := nvcc
NVCCFLAGS :=
CPPFLAGS  := -I . -I .. -I $(CUDA_INSTALL_PATH)/include
CC        := gcc
CXX       := c++
AR        := ar
ARFLAGS   := rucv

ifneq ($(DARWIN),)
	BOOST        ?= /opt/local
	BOOST_INC    := $(BOOST)/include
	BOOST_LIBS   := $(BOOST)/lib
	BOOST_SUFFIX := -mt
	BOOST_INC_PATH := -I $(BOOST_INC)
	BOOST_LIB_PATH := -L $(BOOST_LIBS)
	NVCCFLAGS += -m64
endif

ifeq ($(MPI_LIB),)
	MPI_LIB := $(MPI_INSTALL_PATH)/lib
endif
ifeq ($(MPI_INCLUDE),)
	MPI_INCLUDE := $(MPI_INSTALL_PATH)/include
endif

ifeq ($(dbg),1)
	NVCCFLAGS += -g -G -D_DEBUG -DDEBUG
#	NVCCFLAGS += -g -D_DEBUG -DDEBUG
	CFLAGS += -g -D_DEBUG -DDEBUG
	CXXFLAGS += -g -D_DEBUG -DDEBUG
else
	NVCCFLAGS += -O2 -use_fast_math -DNODEBUG
	CFLAGS += -O2 -ffast-math -DNODEBUG
	CXXFLAGS += -O2 -ffast-math -DNODEBUG
endif

# debug builds are not OK!!!
#NVCCFLAGS += -g -G -D_DEBUG
#NVCCFLAGS += -g -D_DEBUG --device-debug=2
#NVCCFLAGS += --compiler-options -fno-inline
NVCCFLAGS += --ptxas-options=-v
# global mem cached in L2 and L1, default
#NVCCFLAGS += -Xptxas -dlcm=ca
# global mem cached in L2 only
#NVCCFLAGS += -Xptxas -dlcm=cg
#NVCCFLAGS += -maxrregcount ??
#NVCCFLAGS += -ftz=true
#NVCCFLAGS += --keep 
#SMVERSIONFLAGS := -arch=sm_20
#SMVERSIONFLAGS := -arch=sm_13
#SMVERSIONFLAGS := -gencode arch=compute_20,code=sm_20
#SMVERSIONFLAGS := -gencode arch=compute_13,code=sm_13
#SMVERSIONFLAGS := -gencode arch=compute_20,code=sm_20 \
#		  -gencode arch=compute_13,code=sm_13

ifneq ($(arch),)
	SMVERSIONFLAGS = -arch=sm_$(arch)
else
	SMVERSIONFLAGS  = -gencode arch=compute_20,code=sm_20
#       SMVERSIONFLAGS += -gencode arch=compute_13,code=sm_13
endif

CPPFLAGS += -I$(CUQU) $(BOOST_INC_PATH)
LIBS := -L$(CUQU)/lib
LIBS += $(BOOST_LIB_PATH) -lboost_thread$(BOOST_SUFFIX)

# LIBS += -lcuos
# LIBS += -lboost_thread
# LIBS += -L$(MPI_LIB) -lmpi

%: %.o
	$(VERBOSE)$(NVCC) $(NVCCFLAGS) $(CPPFLAGS) $(SMVERSIONFLAGS) $(LIBS) -o $@ $<

%.o: %.cu
	$(VERBOSE)$(NVCC) $(NVCCFLAGS) $(CPPFLAGS) $(SMVERSIONFLAGS) -o $@ -c $<

%.o: %.cpp
	$(VERBOSE)$(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $@ -c $<

%.o: %.c
	$(VERBOSE)$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ -c $<
